/**
 * Preview module
 */
import React from 'react';

import PreviewWidget from './PreviewWidget';
import Phone from './Phone';
import Ruler from './Ruler';
import switchTypes from '../../../../consts/switchTypes';
import editorSize from '../../../../consts/editorSize';

class Preview extends React.Component {
    componentDidMount() {
        this.initElement();
        const { top, left } = this.props;
        const $element = this.elements.canvas;
        this.area = {
            width: parseFloat(editorSize.editor_width),
            height: parseFloat(editorSize.editor_height),
        };

        const $editorMainImg = $element.find('.editor-main-img');
        const $creatorPanel = $element.parents('.creator-panel');
        const scrollTop = editorSize.view.height / 2 - 700;
        const scrollLeft = editorSize.view.width / 2 - 700;

        const mainImgPosition = {
            left: scrollLeft + $creatorPanel.width() / 2 - this.area.width / 2,
            top: scrollTop + $creatorPanel.height() / 2 - this.area.height / 2,
        };

        const mainPhonePosition = {
            left: scrollLeft + $creatorPanel.width() / 2 - this.area.width / 2,
            top: scrollTop + $creatorPanel.height() / 2 - this.area.height / 2,
            'margin-top': -94 - (756 - this.area.height) / 2,
        };

        this.transform = {
            offset_x: mainImgPosition.left + this.area.width / 2,
            offset_y: mainImgPosition.top + this.area.height / 2,
        };

        $editorMainImg.css(mainImgPosition);
        $('.editor-main-phone').css(mainPhonePosition);
        $element.css(_const.view);
    }
    initElement() {
        this.elements = {
            canvas: $(this.refs.canvas),
        };
    }
    render() {
        const { fromTemplate, page, transform, widgets, preview, selectedWidgets, style } = this.props;
        const { singleWidget, singleTimeline } = preview;
        const previewWidgets = singleWidget ? selectedWidgets : widgets;

        let RulerNode = '';
        if (!fromTemplate) {
            RulerNode = <Ruler />;
        }
        return (
          <div>
            <div ref="canvas" className="editor-canvas" data-preview-canvas aria-disabled="false" style={style}>
              <Phone showSnap="false" page={page} />
              {
                previewWidgets.map((widget) => {
                    return (
                      <PreviewWidget key={`${widget.id}-preview`} singleTimeline={singleTimeline} singleWidget={singleWidget} transform={transform} widget={widget} />
                    );
                })
              }
              {RulerNode}
            </div>
          </div>
        );
    }
}

export default Preview;
